﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotSpatial.Topology;
using DotSpatial.Data;
using DotSpatial.Controls;
using DotSpatial.Symbology;

namespace HAGISV2
{
    /// <summary>
    /// 因各种修改原因 现在生成正视图采用自身算法，侧视图采用获取主程点坐标数据
    /// </summary>
    [Serializable]
    public class HydrolicGridLayer : HybridBaseLayer
    {
        public HydrolicGridLayer(string id, HyGrid grid)
            : base(id)
        {

            Configure();
            this.HyGrid = grid;
            if (!GenerateNomalViewGrid()) return;

            this.Boundary =GetNeededGridInfo.TranslateList2DTo3D(_hyGrid,null);
            OnSetInvalidBound();
        }

        public HydrolicGridLayer(string id, HyGrid grid, List<int[,]> boundary)
            : base(id)
        {

            Configure();
            this.HyGrid = grid;
            if (!GenerateNomalViewGrid()) return;

            this.Boundary = GetNeededGridInfo.TranslateList2DTo3D(_hyGrid,boundary);

            OnSetInvalidBound();
        }

        private void Configure()
        {
            BuildDataset();
            _selectedCellIndexes = new List<int>();

            _topColCoordinates = new List<Coordinate>();
            _leftRowCoordinates = new List<Coordinate>();
            _bottomCoordinates = new List<Coordinate>();
            _rightCoordinates = new List<Coordinate>();
            _gridLines = new List<LineSegment>();
            _gridCoordinates = new List<Coordinate>();
            _gridPolygons = new List<Polygon>();
        }

        

        #region 私有变量

        bool _isRegenerate = true;

        HyGrid _hyGrid;

        int[,,] _boundary;

        [NonSerialized]
        List<int> _selectedCellIndexes = new List<int>();
        [NonSerialized]
        List<int[]> _selectedCellIJK = new List<int[]>();

        #endregion

        #region 辅助参数


        //生成面完毕将线，点层置否，便于下次生成
        //生成完成与否的判断标志为面层
        bool IsGeneratedLines = false;
        bool IsGeneratedCoordinates = false;
        bool IsGeneratedPolygons = false;


        #endregion

        #region 公共方法

        public override Extent GetLayerExtent()
        {
            if (!this.IsLoaded)
            {
                return null;
            }

            Extent ex = new Extent();
            if (_ptLayer.DataSet.Features.Count > 0)
            {
                _ptLayer.DataSet.UpdateExtent();
                ex.ExpandToInclude(_ptLayer.Extent);
            }

            if (ex == new Extent())
                return null;

            return ex;
        }

        public void MoveCrossPoint()
        {
 
        }

        public List<Coordinate> GetGridAngularCoordinates()
        {
            List<Coordinate> bounderCoords = new List<Coordinate>();
            bounderCoords.Add(_topColCoordinates[0]);
            bounderCoords.Add(_topColCoordinates[_topColCoordinates.Count - 1]);
            bounderCoords.Add(_bottomCoordinates[_bottomCoordinates.Count - 1]);
            bounderCoords.Add(_bottomCoordinates[0]);
            bounderCoords.Add(_topColCoordinates[0]);
            return bounderCoords;
        }

        public void ResetGridData(HyGrid grid, List<int[,]> boundary)
        {
            _hyGrid = grid;
            if (boundary == null || boundary.Count <= 0)
            {
                return;
            }
            else
            {
                this._boundary = new int[boundary.Count, boundary[0].GetLength(0), boundary[0].GetLength(1)];
                for (int k = 0; k < boundary.Count; k++)
                {
                    for (int j = 0; j < boundary[0].GetLength(0); j++)
                    {
                        for (int i = 0; i < boundary[0].GetLength(1); i++)
                        {
                            this._boundary[k, j, i] = boundary[k][j, i];
                        }
                    }
                }
            }


            this.Update();

        }

        public void Select(IEnvelope tolerant, IEnvelope strict, MFEDITGRIDMODE editMode, bool isShiftRemoved)
        {
            if (!IsLoaded) return;
            IEnvelope env;

            List<IFeature> selectedFeatures = new List<IFeature>();


            switch (editMode)
            {
                case MFEDITGRIDMODE.None:
                    break;
                case MFEDITGRIDMODE.EditByNode:

                    this._ptLayer.Select(tolerant, strict, SelectionMode.Intersects, out env);

                    selectedFeatures.AddRange(this._ptLayer.Selection.ToFeatureList());

                    break;
                case MFEDITGRIDMODE.SelectByCell:
                    if (!isShiftRemoved)
                        this._pyLayer.Select(tolerant, strict, SelectionMode.Intersects, out env);

                    selectedFeatures.AddRange(this._pyLayer.Selection.ToFeatureList());

                    _selectedCellIndexes = new List<int>();
                    int cellIndex;
                    for (int i = 0; i < selectedFeatures.Count; i++)
                    {
                        cellIndex = _pyLayer.DataSet.Features.IndexOf(selectedFeatures[i]);
                        if (cellIndex == -1) continue;
                        _selectedCellIndexes.Add(cellIndex + 1);
                    }


                    //计算选择单元索引
                    ComputeSelectedCellIndexs(ViewLayerIndex - 1);
                    _selectedCellIndexes.Sort();
                    break;
                case MFEDITGRIDMODE.SelectByRowCell:

                    if (!isShiftRemoved)
                        this._pyLayer.Select(tolerant, strict, SelectionMode.Intersects, out env);
                    
                    selectedFeatures.AddRange(this._pyLayer.Selection.ToFeatureList());
                    
                    List<int> rowsIndex = new List<int>();
                    _selectedCellIndexes = new List<int>();
                    int rowIndex;
                    for (int i = 0; i < selectedFeatures.Count; i++)
                    {
                        rowIndex = _pyLayer.DataSet.Features.IndexOf(selectedFeatures[i]);
                        if (rowIndex == -1) continue;
                        rowIndex /= _colCountCell;
                        if (!rowsIndex.Contains(rowIndex))
                        {
                            rowsIndex.Add(rowIndex);

                        }
                    }
                    rowsIndex.Sort();

                    int helper;
                    for (int i = 0; i < rowsIndex.Count; i++)
                    {
                        helper= rowsIndex[i] * _colCountCell;
                        for (int j = 0; j < _colCountCell; j++)
                        {
                            if (_iBound != null)
                            {
                                if (_iBound[rowsIndex[i] , j] == 0) continue;
                            }
                            _selectedCellIndexes.Add(helper + j);

                        }
                    }

                    _pyLayer.Select(_selectedCellIndexes);
                    for (int i = 0; i < _selectedCellIndexes.Count; i++)
                    {
                        _selectedCellIndexes[i]++;
                    }

                    //计算选择单元索引
                    ComputeSelectedCellIndexs(ViewLayerIndex - 1);
                    if (_viewMode == FMAPVIEW.RIGHT)
                        _selectedCellIndexes.Sort();
                    
                    break;
                case MFEDITGRIDMODE.SelectByColCell:
                    if (!isShiftRemoved)
                        this._pyLayer.Select(tolerant, strict, SelectionMode.Intersects, out env);
                    selectedFeatures.AddRange(this._pyLayer.Selection.ToFeatureList());

                    List<int> colsIndex = new List<int>();
                    _selectedCellIndexes = new List<int>();
                    int colIndex;
                    for (int i = 0; i < selectedFeatures.Count; i++)
                    {
                        colIndex = _pyLayer.DataSet.Features.IndexOf(selectedFeatures[i]);
                        if (colIndex == -1) continue;
                        colIndex %= _colCountCell;
                        if (!colsIndex.Contains(colIndex))
                        {
                            colsIndex.Add(colIndex);
                        }
                    }

                    colsIndex.Sort();

                    for (int i = 0; i < colsIndex.Count; i++)
                    {
                        for (int j = 0; j < _rowCountCell; j++)
                        {
                            
                            if (_iBound != null)
                            {
                                if (_iBound[j, colsIndex[i]] == 0) continue;
                            }
                            _selectedCellIndexes.Add(j * _colCountCell + colsIndex[i]);
                        }
                    }
                    _pyLayer.Select(_selectedCellIndexes);
                    for (int i = 0; i < _selectedCellIndexes.Count; i++)
                    {
                        _selectedCellIndexes[i]++;
                    }
                    //计算选择单元索引
                    ComputeSelectedCellIndexs(ViewLayerIndex - 1);
                    //if (_viewMode == FMAPVIEW.RIGHT)
                    //    _selectedCellIndexes.Sort();
                    break;
                case MFEDITGRIDMODE.SelectByLayer:

                    this._pyLayer.SelectAll();

                    break;
                case MFEDITGRIDMODE.AddRow:
                    break;
                case MFEDITGRIDMODE.AddCol:
                    break;
                default:
                    break;
            }


            //选择前清空
            //this._selectedShapes.Clear();
        }

        public override bool OpenLayer()
        {
            this.BuildDataset();

            this.Update();

            this.Render();
            this.DefaultManager.CurrentMap.Invalidate();


            return true;

        }

        public override void ClearSelection()
        {
            SelectedCellIndexes.Clear();
            if (PtLayer.Selection.Count > 0)
                PtLayer.Selection.Clear();
            if (PyLayer.Selection.Count > 0)
                PyLayer.Selection.Clear();
        }


        /// <summary>
        /// 强制绘制自身
        /// </summary>
        public override void Redraw()
        {
            if (_gridLines == null)
                _gridLines = new List<LineSegment>();
            if (_gridCoordinates == null)
                _gridCoordinates = new List<Coordinate>();
            if (_gridPolygons == null)
                _gridPolygons = new List<Polygon>();

            _selectedCellIndexes = new List<int>();

            switch (_viewMode)
            {
                case FMAPVIEW.NORMAL:
                    if (_isRegenerate)
                    {
                        if (!GenerateNomalViewGrid() || !OnSetInvalidBound())
                        {
                            System.Windows.Forms.MessageBox.Show("网格信息重绘失败！");
                            return;
                        }
                    }
                    else if (!OnSetInvalidBound())
                    {
                        System.Windows.Forms.MessageBox.Show("网格信息重绘失败！");
                        _isRegenerate = true;
                        return;
                    }
                    if (_ptLayer != null && _pyLayer != null && _lnLayer != null)
                    {
                        List<IFeature> fs = (List<IFeature>)_ptLayer.DataSet.Features.CloneList();
                        _ptLayer.DataSet.Features.Clear();
                        foreach (IFeature item in fs)
                        {
                            _ptLayer.DataSet.Features.Add(item);
                        }
                        fs = (List<IFeature>)_pyLayer.DataSet.Features.CloneList();
                        _pyLayer.DataSet.Features.Clear();
                        foreach (IFeature item in fs)
                        {
                            _pyLayer.DataSet.Features.Add(item);
                        }
                        fs = (List<IFeature>)_lnLayer.DataSet.Features.CloneList();
                        _lnLayer.DataSet.Features.Clear();
                        foreach (IFeature item in fs)
                        {
                            _lnLayer.DataSet.Features.Add(item);
                        }
                    }
                    break;
                case FMAPVIEW.FRONT:
                    //if(_isRegenerate)
                        if (!GenerateFrontViewGrid(_viewFrontIndex - 1) || !OnSetInvalidBound())
                        {
                            System.Windows.Forms.MessageBox.Show("网格信息重绘失败！");
                            _isRegenerate = true;
                            return;
                        }
                    if (_ptLayer != null && _pyLayer != null)
                    {
                        List<IFeature> fs = (List<IFeature>)_ptLayer.DataSet.Features.CloneList();
                        _ptLayer.DataSet.Features.Clear();
                        foreach (IFeature item in fs)
                        {
                            _ptLayer.DataSet.Features.Add(item);
                        }
                        fs = (List<IFeature>)_pyLayer.DataSet.Features.CloneList();
                        _pyLayer.DataSet.Features.Clear();
                        foreach (IFeature item in fs)
                        {
                            _pyLayer.DataSet.Features.Add(item);
                        }
                        _lnLayer.DataSet.Features.Clear();
                    }
                    break;
                case FMAPVIEW.RIGHT:
                    //if(_isRegenerate)
                        if (!GenerateRightViewGrid(_viewRightIndex - 1) || !OnSetInvalidBound())
                        {
                            System.Windows.Forms.MessageBox.Show("网格信息重绘失败！");
                            _isRegenerate = true;
                            return;
                        }
                    if (_ptLayer != null && _pyLayer != null)
                    {
                        List<IFeature> fs = (List<IFeature>)_ptLayer.DataSet.Features.CloneList();
                        _ptLayer.DataSet.Features.Clear();
                        foreach (IFeature item in fs)
                        {
                            _ptLayer.DataSet.Features.Add(item);
                        }
                        fs = (List<IFeature>)_pyLayer.DataSet.Features.CloneList();
                        _pyLayer.DataSet.Features.Clear();
                        foreach (IFeature item in fs)
                        {
                            _pyLayer.DataSet.Features.Add(item);
                        }
                        _lnLayer.DataSet.Features.Clear();
                    }
                    break;
                default:
                    break;
            }

            _isRegenerate = true;

            if (_ptLayer != null && _pyLayer != null && _lnLayer != null)
            {
                _ptLayer.DataSet.InitializeVertices();
                _lnLayer.DataSet.InitializeVertices();
                _pyLayer.DataSet.InitializeVertices();

                _ptLayer.Invalidate();
                _lnLayer.Invalidate();
                _pyLayer.Invalidate();
            }
        }



        public override void Select(IEnvelope tolerant, IEnvelope strict, DotSpatial.Symbology.SelectionMode selectionMode)
        {

        }

        public override void Render()
        {
            base.Render();

            _lnLayer.SelectionEnabled = false;
            _ptLayer.SelectionEnabled = false;
            _pyLayer.SelectionEnabled = false;

            _lnLayer.Symbolizer = new LineSymbolizer(System.Drawing.Color.Transparent, 1);
            _lnLayer.SelectionSymbolizer = new LineSymbolizer(System.Drawing.Color.Black, 1);

            _ptLayer.Symbolizer = new PointSymbolizer(System.Drawing.Color.Transparent, DotSpatial.Symbology.PointShape.Rectangle, 5);
            _ptLayer.SelectionSymbolizer = new PointSymbolizer(System.Drawing.Color.Red, DotSpatial.Symbology.PointShape.Rectangle, 5);

            _pyLayer.Symbolizer = new PolygonSymbolizer(System.Drawing.Color.Transparent, System.Drawing.Color.Black);
            _pyLayer.SelectionSymbolizer = new PolygonSymbolizer(System.Drawing.Color.Blue, System.Drawing.Color.Black);

            OnSetVisible();
        }

        public override void StopRender()
        {
            this.ClearSelection();
            
            base.StopRender();
        }

        #endregion

        #region properties

        [NonSerialized]
        List<Polygon> _gridPolygons;

        public List<Polygon> GridPolygons
        {
            get { return _gridPolygons; }
            set { _gridPolygons = value; }
        }

        [NonSerialized]
        List<Coordinate> _gridCoordinates;
        /// <summary>
        /// 网格坐标点，左上角为0，0 依次向右向下排列
        /// </summary>
        public List<Coordinate> GridCoordinates
        {
            get { return _gridCoordinates; }
            set { _gridCoordinates = value; }
        }


        [NonSerialized]
        List<LineSegment> _gridLines;
        /// <summary>
        /// 添加顺序自上向下，自左向右，先横再丨
        /// </summary>
        public List<LineSegment> GridLines
        {
            get { return _gridLines; }
            set { _gridLines = value; }
        }

        List<Coordinate> _topColCoordinates;
        /// <summary>
        /// 最上方一行坐标点信息
        /// </summary>
        public List<Coordinate> TopColCoordinates
        {
            get { return _topColCoordinates; }
            set { _topColCoordinates = value; }
        }

        List<Coordinate> _leftRowCoordinates;
        /// <summary>
        /// 最左方一列坐标点信息
        /// </summary>
        public List<Coordinate> LeftRowCoordinates
        {
            get { return _leftRowCoordinates; }
            set { _leftRowCoordinates = value; }
        }

        List<Coordinate> _bottomCoordinates;

        public List<Coordinate> BottomCoordinates
        {
            get { return _bottomCoordinates; }
            set { _bottomCoordinates = value; }
        }

        List<Coordinate> _rightCoordinates;

        public List<Coordinate> RightCoordinates
        {
            get { return _rightCoordinates; }
            set { _rightCoordinates = value; }
        }

        // 一列中行单元个数
        int _rowCountCell;

        // 一行中列单元个数
        int _colCountCell;


        int _viewLayerIndex = 1;
        int _viewFrontIndex = 1;
        int _viewRightIndex = 1;
        /// <summary>
        /// 索引从1开始
        /// </summary>
        public int ViewLayerIndex
        {
            get
            {
                switch (_viewMode)
                {
                    case FMAPVIEW.NORMAL:
                        return _viewLayerIndex > 1 ? _viewLayerIndex : 1;
                    case FMAPVIEW.FRONT:
                        return _viewFrontIndex > 1 ? _viewFrontIndex : 1;
                    case FMAPVIEW.RIGHT:
                        return _viewRightIndex > 1 ? _viewRightIndex : 1;
                    default:
                        return 1;
                }
            }
            set
            {
                if (value <= 0) return;
                switch (_viewMode)
                {
                    case FMAPVIEW.NORMAL:
                        if (value == _viewLayerIndex || value > _hyGrid.LayersCount) return;
                        _viewLayerIndex = value;

                        break;
                    case FMAPVIEW.FRONT:
                        if (value == _viewFrontIndex || value > _hyGrid.RowsCount) return;
                        _viewFrontIndex = value;
                        break;
                    case FMAPVIEW.RIGHT:
                        if (value == _viewRightIndex || value > _hyGrid.ColsCount) return;
                        _viewRightIndex = value;
                        break;
                    default:
                        return;
                }
                OnViewLayerChanged();
            }
        }




        [NonSerialized]
        int[,] _iBound;

        public int[,] IBound
        {
            get { return _iBound; }
            set { _iBound = value; }
        }

        #endregion

        #region method 私有及保护的

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ROWCOLIndex">起始索引为0</param>
        /// <returns></returns>
        bool ComputeSelectedCellIndexs(int ROWCOLIndex)
        {
            switch (_viewMode)
            {
                case FMAPVIEW.NORMAL:
                    for (int i = 0; i < _selectedCellIndexes.Count;i++ )
                    {
                        _selectedCellIndexes[i] += (_hyGrid.ColsCount * _hyGrid.RowsCount) * ROWCOLIndex;
                    }
                    break;
                case FMAPVIEW.FRONT:
                    int f;
                    for (int i = 0; i < _selectedCellIndexes.Count;i++ )
                    {
                        f=_selectedCellIndexes[i];
                        _selectedCellIndexes[i] = (_hyGrid.ColsCount * _hyGrid.RowsCount) * ((f - 1) / _colCountCell) + ROWCOLIndex * _colCountCell + (f - 1) % _colCountCell+1;
                    }

                    break;
                case FMAPVIEW.RIGHT:
                    int r;
                    for (int i = 0; i < _selectedCellIndexes.Count;i++ )
                    {
                        r=_selectedCellIndexes[i];
                        //_selectedCellIndexes[i] = (_hyGrid.ColsCount * _hyGrid.RowsCount) * ((r - 1) / _colCountCell) + ROWCOLIndex + (_colCountCell- (r - 1) % _colCountCell-1)*_hyGrid.ColsCount+1;
                        _selectedCellIndexes[i] = (_hyGrid.ColsCount * _hyGrid.RowsCount) * ((r - 1) / _colCountCell) + ROWCOLIndex + ((r - 1) % _colCountCell) * _hyGrid.ColsCount + 1;
                    }
                    
                    break;
                default:
                    break;
            }
            

            return true;
        }

        public void ComputeSelectedCellIndexs(ref int index)
        {
            int ROWCOLIndex=ViewLayerIndex - 1;
            switch (_viewMode)
            {
                case FMAPVIEW.NORMAL:
                        index += (_hyGrid.ColsCount * _hyGrid.RowsCount) * ROWCOLIndex;
                    break;
                case FMAPVIEW.FRONT:

                    index = (_hyGrid.ColsCount * _hyGrid.RowsCount) * ((index - 1) / _colCountCell) + ROWCOLIndex * _colCountCell + (index - 1) % _colCountCell + 1;

                    break;
                case FMAPVIEW.RIGHT:

                    index = (_hyGrid.ColsCount * _hyGrid.RowsCount) * ((index - 1) / _colCountCell) + ROWCOLIndex + ((index - 1) % _colCountCell) * _hyGrid.ColsCount + 1;
                    
                    break;
                default:
                    break;
            }
        }



        protected override void OnViewModeChanged()
        {
            this.Redraw();
        }

        void OnViewLayerChanged()
        {
            this._isRegenerate = false;
            this.Redraw();
        }


        protected void OnSetHyGrid()
        {
            if (this.IsLoaded)
            {
                this.Redraw();
            }

        }

        /// <summary>
        /// 设置无效区
        /// </summary>
        /// <returns></returns>
        bool OnSetInvalidBound()
        {
            try
            {
                switch (_viewMode)
                {
                    case FMAPVIEW.NORMAL:
                        _iBound = new int[_hyGrid.RowsCount, _hyGrid.ColsCount];
                        for (int j = 0; j < _hyGrid.RowsCount; j++)
                        {
                            for (int i = 0; i < _hyGrid.ColsCount; i++)
                            {
                                _iBound[j, i] = _boundary[_viewLayerIndex - 1, j, i];
                            }
                        }
    
                        

                        break;
                    case FMAPVIEW.FRONT:
                        _iBound = new int[_hyGrid.LayersCount, _hyGrid.ColsCount];
                        for (int k = 0; k < _hyGrid.LayersCount; k++)
                        {
                            for (int i = 0; i < _hyGrid.ColsCount; i++)
                            {
                                _iBound[k, i] = _boundary[k,  _viewFrontIndex - 1,i];
                            }
                        }

                        break;
                    case FMAPVIEW.RIGHT:
                        _iBound = new int[_hyGrid.LayersCount, _hyGrid.RowsCount];
                        for (int k = 0; k < _hyGrid.LayersCount; k++)
                        {
                            for (int j = 0; j < _hyGrid.RowsCount; j++)
                            {
                                //_iBound[k, _hyGrid.RowsCount- j-1] = _boundary[k,j,  _viewRightIndex - 1];
                                _iBound[k, j ] = _boundary[k, j, _viewRightIndex - 1];
                            }
                        }
                        break;
                    default:
                        break;
                }

                

                int count = 0;
                for (int i = 0; i < _iBound.GetLength(0); i++)
                {
                    for (int j = 0; j < _iBound.GetLength(1); j++)
                    {
                        if (_iBound[i, j] == 0)
                            _pyFeatureSet.Features[count].BasicGeometry = new Polygon(new List<Coordinate>());
                        else
                            _pyFeatureSet.Features[count].BasicGeometry = _gridPolygons[count];
                        count++;
                    }
                }

            }
            catch { return false; }
            return true;
        }


        protected void OnSetBoundary()
        {

            if (this.IsLoaded)
            {
                OnSetInvalidBound();
                _pyLayer.DataSet.InitializeVertices();
                _pyLayer.Invalidate();
            }

        }

        protected override void OnSetVisible()
        {
            if (!this.IsLoaded)
            {
                return;

            }

            this._ptLayer.IsVisible = this.Visible;
            this._lnLayer.IsVisible = this.Visible;
            this._pyLayer.IsVisible = this.Visible;
        }


        protected override void BuildDataset()
        {
            _ptFeatureSet = new FeatureSet(FeatureType.Point);

            _pyFeatureSet = new FeatureSet(FeatureType.Polygon);

            _lnFeatureSet = new FeatureSet(FeatureType.Line);

        }

        bool GenerateFrontViewGrid(int rowIndex)
        {
            //不进行线段生成
            //生成点
            _gridCoordinates.Clear();
            _ptFeatureSet.Features.Clear();
            _pyFeatureSet.Features.Clear();
            _gridPolygons.Clear();

            if (_hyGrid.LayersCount <= 0 || _hyGrid.ColsCount <= 0) return false;

            Coordinate helpCoord;
            //int row = _hyGrid.RowsCount - rowIndex;
            int row = rowIndex;
            for (int k = 0; k <= _hyGrid.LayersCount; k++)
            {
                for (int i = 0; i <= _hyGrid.ColsCount; i++)
                {
                    helpCoord = HyGrid.Grid3DCoordinates[k, row, i];
                    _gridCoordinates.Add(new Coordinate(helpCoord.X, helpCoord.Z));
                }
            }

            _ptFeatureSet.Features.Add(_gridCoordinates);
            _colCountCell = _hyGrid.ColsCount;
            _rowCountCell = _hyGrid.LayersCount;

            Polygon cellPolygon;

            for (int i = 0; i < _hyGrid.LayersCount; i++)
            {
                for (int j = 0; j < _hyGrid.ColsCount; j++)
                {
                    cellPolygon = GetCellPolygon(i, j);

                    if (cellPolygon == null) return false;

                    _gridPolygons.Add(cellPolygon);

                    _pyFeatureSet.Features.Add(cellPolygon);
                }
            }



            return true;
        }

        bool GenerateRightViewGrid(int colIndex)
        {
            //不进行线段生成
            //生成点
            _gridCoordinates.Clear();
            _ptFeatureSet.Features.Clear();
            _pyFeatureSet.Features.Clear();
            _gridPolygons.Clear();

            if (_hyGrid.LayersCount <= 0 || _hyGrid.RowsCount <= 0) return false;
            

            Coordinate helpCoord;
            for (int k = 0; k <= _hyGrid.LayersCount; k++)
            {
                for (int j = 0; j <= _hyGrid.RowsCount; j++)
                {
                    helpCoord = HyGrid.Grid3DCoordinates[k, j, colIndex];
                    _gridCoordinates.Add(new Coordinate(helpCoord.Y, helpCoord.Z));
                }
            }

            _ptFeatureSet.Features.Add(_gridCoordinates);
            _colCountCell = _hyGrid.RowsCount;
            _rowCountCell = _hyGrid.LayersCount;

            Polygon cellPolygon;

            for (int i = 0; i < _hyGrid.LayersCount; i++)
            {
                for (int j = 0; j < _hyGrid.RowsCount; j++)
                {
                    cellPolygon = GetCellPolygon(i, j);

                    if (cellPolygon == null) return false;

                    _gridPolygons.Add(cellPolygon);

                    _pyFeatureSet.Features.Add(cellPolygon);
                }
            }



            return true;
        }


        bool GenerateNomalViewGrid()
        {
            
            if (!GenerateGridBounder() || !GenerateGridLines() || !GenerateGridCoordinates() || !GenerateGridPolygons())
                return false;

            return true;
        }


        /// <summary>
        /// 生成点层
        /// </summary>
        /// <returns></returns>
        bool GenerateGridCoordinates()
        {
            if (!IsGeneratedLines)
            {
                if (!GenerateGridLines()) return false;
            }
            try
            {
                Coordinate intersectCoordinate;
                _gridCoordinates.Clear();
                _ptFeatureSet.Features.Clear();
                if (_rowCountCell <= 0 || _colCountCell <= 0) return false;
                //添加top
                _gridCoordinates.AddRange(_topColCoordinates);

                for (int i = 1; i < _rowCountCell; i++)
                {
                    //添加left
                    _gridCoordinates.Add(_leftRowCoordinates[i]);

                    for (int j = _rowCountCell + 2; j < _gridLines.Count - 1; j++)
                    {
                        intersectCoordinate = _gridLines[i].Intersection(_gridLines[j]);
                        _gridCoordinates.Add(intersectCoordinate);
                    }

                    //添加right
                    _gridCoordinates.Add(_rightCoordinates[i]);
                }

                //添加bot
                _gridCoordinates.AddRange(_bottomCoordinates);

                _ptFeatureSet.Features.Add(_gridCoordinates);
                //_ptLayer.DataSet = _ptFeatureSet;
            }
            catch
            {
                return false;
            }


            IsGeneratedLines = true;
            IsGeneratedCoordinates = true;
            IsGeneratedPolygons = false;

            return true;
        }

        /// <summary>
        /// 生成线层
        /// </summary>
        /// <returns></returns>
        bool GenerateGridLines()
        {
            try
            {
                Coordinate[] twoCoordinates;
                _lnFeatureSet.Features.Clear();
                _gridLines.Clear();
                for (int i = 0; i <= _rowCountCell; i++)
                {
                    twoCoordinates = new Coordinate[2] { _leftRowCoordinates[i], _rightCoordinates[i] };

                    _gridLines.Add(new LineSegment(_leftRowCoordinates[i], _rightCoordinates[i]));

                    _lnFeatureSet.AddFeature(new LineString(twoCoordinates));
                    //_lnLayer.DataSet = _lnFeatureSet;
                }
                for (int i = 0; i <= _colCountCell; i++)
                {
                    twoCoordinates = new Coordinate[2] { _topColCoordinates[i], _bottomCoordinates[i] };

                    _gridLines.Add(new LineSegment(_topColCoordinates[i], _bottomCoordinates[i]));

                    _lnFeatureSet.AddFeature(new LineString(twoCoordinates));
                }

            }
            catch
            {
                return false;
            }

            IsGeneratedLines = true;
            IsGeneratedCoordinates = false;
            IsGeneratedPolygons = false;

            return true;
        }

        /// <summary>
        /// 生成面层
        /// </summary>
        /// <returns></returns>
        bool GenerateGridPolygons()
        {
            try
            {
                Polygon cellPolygon;
                _pyFeatureSet.Features.Clear();
                _gridPolygons.Clear();

                for (int i = 0; i < _rowCountCell; i++)
                {
                    for (int j = 0; j < _colCountCell; j++)
                    {
                        cellPolygon = GetCellPolygon(i, j);

                        if (cellPolygon == null) return false;

                        _gridPolygons.Add(cellPolygon);

                        _pyFeatureSet.Features.Add(cellPolygon);
                    }
                }




            }
            catch
            {
                return false;
            }

            //生成面完毕将线，点层置否，便于下次生成
            //生成完成与否的判断标志为面层
            IsGeneratedLines = false;
            IsGeneratedCoordinates = false;
            IsGeneratedPolygons = true;

            return true;
        }
        /// <summary>
        /// 获取单元格LineString
        /// </summary>
        /// <param name="row"></param>
        /// <param name="col"></param>
        /// <returns></returns>
        Polygon GetCellPolygon(int row, int col)
        {
            if (row < 0 || col < 0 || row >= _rowCountCell || col >= _colCountCell) return null;
            Coordinate[] cellCoordinates = new Coordinate[5];
            try
            {
                cellCoordinates[0] = _gridCoordinates[row * (_colCountCell + 1) + col];
                cellCoordinates[1] = _gridCoordinates[row * (_colCountCell + 1) + col + 1];
                cellCoordinates[2] = _gridCoordinates[(row + 1) * (_colCountCell + 1) + col + 1];
                cellCoordinates[3] = _gridCoordinates[(row + 1) * (_colCountCell + 1) + col];
                cellCoordinates[4] = cellCoordinates[0];
            }
            catch
            {
                return null;
            }


            return new Polygon(new LinearRing(cellCoordinates));
        }

        /// <summary>
        /// 构建各边界点
        /// </summary>
        /// <returns></returns>
        bool GenerateGridBounder()
        {
            _topColCoordinates.Clear();
            _leftRowCoordinates.Clear();
            _rightCoordinates.Clear();
            _bottomCoordinates.Clear();

            try
            {
                if (_hyGrid.ColCoords.Length <= 0 || _hyGrid.RowCoords.Length <= 0) return false;
                Vector xVec;
                Vector yVec;
                if (_hyGrid.RotationZ % 360 == 0)
                {
                    xVec = new Vector(new Coordinate(0, 0), new Coordinate(1, 0));
                    yVec = new Vector(new Coordinate(0, 0), new Coordinate(0, 1));
                }
                else
                {
                    xVec = new Vector(Math.Cos(_hyGrid.RotationZ / 180 * Math.PI), Math.Sin(_hyGrid.RotationZ / 180 * Math.PI), 0);
                    yVec = new Vector(Math.Cos(_hyGrid.RotationZ / 180 * Math.PI + Math.PI / 2), Math.Sin(_hyGrid.RotationZ / 180 * Math.PI + Math.PI / 2), 0);
                }

                for (int i = _hyGrid.RowCoords.Length - 1; i >= 0; i--)
                {
                    //_leftRowCoordinates.Add(new Coordinate(_hyGrid.OrgX + yVec.X * (_hyGrid.RowCoords[i] - _hyGrid.OrgX), _hyGrid.OrgY + yVec.Y * (_hyGrid.RowCoords[i] - _hyGrid.OrgY)));
                    _leftRowCoordinates.Add(new Coordinate(_hyGrid.OrgX + yVec.X * _hyGrid.RowCoords[i], _hyGrid.OrgY + yVec.Y * _hyGrid.RowCoords[i]));

                }
                for (int i = 0; i < _hyGrid.ColCoords.Length; i++)
                {
                    //_bottomCoordinates.Add(new Coordinate(_hyGrid.OrgX + xVec.X * (_hyGrid.ColCoords[i] - _hyGrid.OrgX), _hyGrid.OrgY + xVec.Y * (_hyGrid.ColCoords[i] - _hyGrid.OrgY)));
                    _bottomCoordinates.Add(new Coordinate(_hyGrid.OrgX + xVec.X * _hyGrid.ColCoords[i], _hyGrid.OrgY + xVec.Y * _hyGrid.ColCoords[i] ));
                }

                Vector vector = new Vector(_bottomCoordinates[0], _bottomCoordinates[_bottomCoordinates.Count - 1]);

                for (int i = 0; i < _leftRowCoordinates.Count; i++)
                {
                    _rightCoordinates.Add(_leftRowCoordinates[i] + vector);
                }
                vector = new Vector(_leftRowCoordinates[_leftRowCoordinates.Count - 1], _leftRowCoordinates[0]);
                for (int i = 0; i < _bottomCoordinates.Count; i++)
                {
                    _topColCoordinates.Add(_bottomCoordinates[i] + vector);
                }
                _rowCountCell = _leftRowCoordinates.Count - 1;
                _colCountCell = _topColCoordinates.Count - 1;

            }
            catch
            {
                return false;
            }
            return true;
        }

        #endregion

        #region 公共属性

        /// <summary>
        /// 行选模式所选格位置信息
        /// </summary>
        public List<int> SelectedCellIndexes
        {
            get { return _selectedCellIndexes; }
        }

        /// <summary>
        /// 所选格KJI位置信息
        /// </summary>
        public List<int[]> SelectedCellIJK
        {
            get { return _selectedCellIJK; }
        }

        /// <summary>
        /// 用于表示基础的网格设置数据
        /// </summary>
        public HyGrid HyGrid
        {
            get { return _hyGrid; }
            set
            {
                _hyGrid = value;

                this.OnSetHyGrid();

            }
        }

        /// <summary>
        /// 网格单元有效性
        /// </summary>
        public int[,,] Boundary
        {
            get { return _boundary; }

            set
            {
                this._boundary = value;
                this.OnSetBoundary();
            }

        }

        #endregion
    }
}
